/**   
 * @Title: ResetPasswordActivity.java 
 * @Package: com.rename.icode.activity 
 * @Description: Administrator版权所有
 * @author Administrator  
 * @date 2015-2-12 下午4:05:13 
 * @version  
 */

package com.rename.icode.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.rename.icode.R;
import com.rename.icode.utils.HttpURLTools;
import com.rename.icode.view.ClearEditText;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

/**
 * @Description 实现了...功能
 * @author Administrator
 * @date 2015-2-12 下午4:05:13
 * @version V1.0
 */

public class ResetPasswordActivity extends ActivitySupport {

	private static final String TAG = "ResetPasswordActivity";
	private ClearEditText mUsernameText;
	private Button mEnsureSetBtn = null;
	private ImageView mWaitVeriCodeImg = null;
	private long mExitTime = 0;
	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_reset_password);

		init();
	}

	protected void init() {
		getICodeApplication().addActivity(this);

		mUsernameText = (ClearEditText) findViewById(R.id.reset_user_name);
		mEnsureSetBtn = (Button) findViewById(R.id.ensure_reset_psd_btn);
		mWaitVeriCodeImg = (ImageView) findViewById(R.id.waiting_veri_code_img);

		// mUsernameText.setText(StringUtil.getCellphoneByName(AppConfigManager.getInstance().getUsername()));
		mUsernameText.setText("18862301107");

		mEnsureSetBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

//				if (checkCellphone()) {
//					String username = StringUtil
//							.getNameByCellphone(mUsernameText.getText()
//									.toString().trim());
//					mWaitVeriCodeImg.setVisibility(View.VISIBLE);
//					GetRequestIdTask task = new GetRequestIdTask(
//							(AnimationDrawable) mWaitVeriCodeImg
//									.getBackground());
//					task.execute(username);
//					mEnsureSetBtn
//							.setBackgroundResource(R.drawable.green_button_frame_pressed);
//					mEnsureSetBtn.setClickable(false);
//				}
			}
		});
	}

	private boolean checkCellphone() {
		// return ValidateUtil.isMobileNumber(mUsernameText);
		return true;
	}
	
	public String getReqIdUrl() {
//		String appServerIp = AppConfigManager.getInstance().getServer().getAppSrvHost();
//		int appServerPort = AppConfigManager.getInstance().getServer().getAppSrvPort();
		String appServerIp = "";
		int appServerPort = 8080;
		return "http://" + appServerIp + ":" + appServerPort + "/app/reset_pwd_req?";
    }
	
	private class GetRequestIdTask extends AsyncTask<String, Integer, Integer>{

    	AnimationDrawable sendRequestIdAnim = null;
    	String des = null;
    	String requestId = null;
    	String userName = null;
    	private GetRequestIdTask(AnimationDrawable animationDrawable){
    		mWaitVeriCodeImg.setVisibility(View.VISIBLE);
    		this.sendRequestIdAnim = animationDrawable;
    	}
		@Override
		protected void onPreExecute() {
			try {//Avoiding APP Crash.
				super.onPreExecute();
				this.sendRequestIdAnim.start();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		protected Integer doInBackground(String... params) {
			
//			AppConfigManager.getInstance().resolvServer();
			String reqIdUrl = getReqIdUrl();
			Log.i(TAG, "send http resqust socket:"+reqIdUrl+",params[0]:"+params[0]);
			
//			String result = new String(ImageUtil.getBytesFromUrl(reqIdUrl, Constants.DISCOVERY_TIMEOUT));
			String result = "";
			Log.i(TAG,"get request id result:"+result);
			JSONTokener jsonParser1 = new JSONTokener(result);
			JSONObject resp1 = null;
			int returnCode  = -1;
			String codeImage = null;
			String description = null;
		    try {
				resp1 = (JSONObject) jsonParser1.nextValue();
				returnCode = resp1.getInt("return_code");
				requestId = resp1.getString("reqid");
				codeImage = resp1.getString("codeimage");
				description = resp1.getString("description");
				des = description;
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		    if(returnCode == 0){
		    	//request id send success
		    	StringBuilder sb = new StringBuilder();
		    	sb.append("reqid=");
		    	sb.append(requestId);
		    	sb.append("&");
		    	sb.append("username=");
		    	userName = params[0];
		    	sb.append(userName);
		    	
//				String appServerIp = AppConfigManager.getInstance().getServer().getAppSrvHost();
//				int appServerPort = AppConfigManager.getInstance().getServer().getAppSrvPort();
				String appServerIp = "";
				int appServerPort = 8080;
				String reqUrl = "http://" + appServerIp + ":" + appServerPort + "/app/reset_pwd_req";

		    	try {
		    		Log.i(TAG,"send request id and user name:"+sb.toString());
		    		result = HttpURLTools.sendHttpPost(reqUrl, sb.toString());
				} catch (Exception e) {
					e.printStackTrace();
					result = "exception";
				}
		    	Log.i(TAG,"send request id and user name, result:"+result);
		    }else if(returnCode == 1){
		    	//fail
		    	Toast.makeText(mContext, getString(R.string.server_error_try_later), Toast.LENGTH_SHORT).show();
		    }
		    JSONTokener jsonParser2 = new JSONTokener(result);
			JSONObject resp2 = null;
			int returnCode2  = -1;
			
		    try {
				resp2 = (JSONObject) jsonParser2.nextValue();
				returnCode2 = resp2.getInt("return_code");
				des = resp2.getString("description");
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		    
			return returnCode2;
		}
		@Override
		protected void onPostExecute(Integer result) {
			this.sendRequestIdAnim.stop();
			mWaitVeriCodeImg.setVisibility(View.GONE);
			if(result == 0){
		    	//SMS verify code send successfully.
				//intent to input new password interface.
				finish();
//				showToast(getString(R.string.sms_verification_code_send_success));
				Intent intent = new Intent(mContext, InputNewPasswordActivity.class);
				intent.putExtra("request_id",requestId);
				intent.putExtra("user_name",userName);
				mContext.startActivity(intent);
		    }else{
		    	//fail,hint reminding message.
		    	Log.i(TAG, "send fail,description is:"+des);
		    	if(des.contains("user is not registered")){
//		    		showToast(getString(R.string.user_do_not_register));
		    	}else{
//		    		showToast(des);
		    	}
		    }
			Log.i(TAG,"send request id result:"+result);
			mEnsureSetBtn.setBackgroundResource(R.drawable.green_button_frame_pressed);
			mEnsureSetBtn.setClickable(true);
			super.onPostExecute(result);
		}

    	
    }
}
